{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from mxnet import autograd, nd"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "生成数据集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_inputs = 2\n",
    "num_examples = 1000\n",
    "true_w = [2, -3.4]\n",
    "true_b = 4.2\n",
    "features = nd.random.normal(scale=1, shape=(num_examples, num_inputs))\n",
    "labels = true_w[0]*features[:, 0] + true_w[1]*features[:, 1] + true_b\n",
    "labels += nd.random.normal(scale=0.01, shape=labels.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "读取数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "from mxnet.gluon import data as gdata\n",
    "\n",
    "batch_size = 10\n",
    "dataset = gdata.ArrayDataset(features, labels)\n",
    "data_iter = gdata.DataLoader(dataset, batch_size, shuffle=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "[[ 0.9014263   1.0593758 ]\n",
      " [ 0.19248743 -0.34041473]\n",
      " [ 1.1869111   0.25542077]\n",
      " [-1.4979134   0.35245466]\n",
      " [-0.7661254   1.343197  ]\n",
      " [ 0.5365119   0.5021193 ]\n",
      " [ 1.733211   -0.0860012 ]\n",
      " [-0.04583286  1.3572003 ]\n",
      " [-0.24696043 -0.97141784]\n",
      " [-0.730555   -0.01439195]]\n",
      "<NDArray 10x2 @cpu(0)> \n",
      "[ 2.390382    5.746613    5.7028675   0.0114568  -1.8848652   3.5662966\n",
      "  7.9535317  -0.49652398  7.006743    2.788939  ]\n",
      "<NDArray 10 @cpu(0)>\n"
     ]
    }
   ],
   "source": [
    "for X, y in data_iter:\n",
    "    print(X, y)\n",
    "    break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "from mxnet.gluon import nn\n",
    "\n",
    "net = nn.Sequential()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
    "net.add(nn.Dense(1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "初始化模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/senmu/opt/anaconda3/envs/gluon/lib/python3.6/site-packages/mxnet/gluon/parameter.py:862: UserWarning: Parameter 'dense4_bias' is already initialized, ignoring. Set force_reinit=True to re-initialize.\n",
      "  v.initialize(None, ctx, init, force_reinit=force_reinit)\n"
     ]
    }
   ],
   "source": [
    "from mxnet import init\n",
    "net.initialize(init.Normal(sigma=0.01))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义损失函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "from mxnet.gluon import loss as gloss\n",
    "\n",
    "loss =  gloss.L2Loss()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义优化算法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "from mxnet import gluon\n",
    "trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate':0.03})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "训练模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, loss: 0.035170\n",
      "epoch 2, loss: 0.000127\n",
      "epoch 3, loss: 0.000049\n",
      "epoch 4, loss: 0.000049\n",
      "epoch 5, loss: 0.000049\n"
     ]
    }
   ],
   "source": [
    "num_epochs = 5\n",
    "for epoch in range(1, num_epochs + 1):\n",
    "    for X, y in data_iter:\n",
    "        with autograd.record():\n",
    "            l = loss(net(X), y)\n",
    "        l.backward()\n",
    "        trainer.step(batch_size)\n",
    "    l = loss(net(features), labels)\n",
    "    print('epoch %d, loss: %f' % (epoch, l.mean().asnumpy()))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
